package com.CatTalkApi.Servlet;
//https://blog.csdn.net/u010395242/article/details/52604784/

import com.CatTalkApi.DAO.DataBaseContext;
import com.CatTalkApi.DAO.UsrInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

//必须使用Json来进行传输数据，要不然解析不了，建议使用Post进行传递数据
//由于我们前后端分离，并且访问端口和域名不一致，所以我们要跨域
@WebServlet("/UsrLogin")
public class UsrLoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/json;charset=UTF-8");

        System.out.println("UsrLogin Method: " + req.getMethod());
        //配置跨域
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        resp.setHeader("Access-Control-Allow-Headers", "authorization, content-type,token,identify");
        resp.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        resp.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        //https://blog.csdn.net/m0_67401746/article/details/123420769

        //只处理POST请求，OPITION请求因为要测试所以无法完成
        if (req.getMethod().equals("POST")) {
            JSONObject jsonObject = JsonReader.receivePost(req);

            System.out.println("捕捉到了数据JSON: " + jsonObject.toJSONString());
            System.out.println("捕捉到了数据ID: " + jsonObject.get("usrID"));

            String usrID = (String) jsonObject.get("usrID");
            String usrPwd = (String) jsonObject.get("usrPwd");

            //在数据库中查询一下用户信息
            ResultSet resultSet = null;
            UsrInfo usrInfo = new UsrInfo();
            int count = 0;
            try {
                String sql = "SELECT * FROM `usrinfo` WHERE Name = '%s' And UsrPwd = '%s'";
                System.out.println("执行的SQL语句" + String.format(sql, usrID, usrPwd));
                resultSet = DataBaseContext.getInstance().GetStmt().executeQuery(String.format(sql, usrID, usrPwd));
                resultSet.last();

                count = resultSet.getRow();

                if (count != 0) {
                    //用户信息
                    usrInfo.Name = resultSet.getString("Name");
                    usrInfo.Gender = resultSet.getString("Gender");
                    usrInfo.Description = resultSet.getString("Description");
                    usrInfo.ID = Integer.parseInt(resultSet.getString("UsrInfo_ID"));

                    //保存登录信息30天
                    Cookie newCookie = new Cookie("unmaeID", String.valueOf(usrInfo.ID));
                    newCookie.setPath("/");
                    newCookie.setMaxAge(30 * 24 * 60 * 30);
                    newCookie.setDomain("localhost");
                    resp.addCookie(newCookie);
                }

                resultSet.close();
                DataBaseContext.getInstance().Close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            if (count != 0) {
                resp.setStatus(200);
                resp.getWriter().write(JSON.toJSONString(usrInfo));
            } else {
                //当登录失败Status为423
                resp.setStatus(423);
            }
        }
    }
}
